package app

import (
	"cloud-navigation/app/common/request"
	"cloud-navigation/app/common/response"
	"cloud-navigation/app/models"
	"cloud-navigation/app/services"
	"cloud-navigation/global"
	"cloud-navigation/utils"
	"fmt"
	"net/smtp"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
)

// 获取控制台信息
func Info(c *gin.Context) {
	var (
		admin, nav, visit int64
	)
	db := global.App.DB
	db.Table("admins").Count(&admin)
	db.Table("navigations").Count(&nav)
	db.Table("visits").Count(&visit)
	response.Success(c, gin.H{"admin": admin, "nav": nav, "visits": visit})
}

// 获取近30天访问详情
func Visit(c *gin.Context) {
	var (
		visits []models.Visits
	)
	//获取当前时间
	now := time.Now()
	now = now.AddDate(0, 0, 1)
	now = time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location())
	// 计算30天前
	ago := now.AddDate(0, 0, -30)

	// 查询数据
	err := global.App.DB.Where("created_at >= ?", ago).Find(&visits).Error
	if err != nil {
		response.BusinessFail(c, "查询失败")
		return
	}
	// 组合数据
	info := make(map[string]int64)
	for i := 0; i < 30; i++ {
		date := ago.AddDate(0, 0, i)
		info[date.Format("2006-01-02")] = 0
	}
	for _, v := range visits {
		date := v.CreatedAt.Format("2006-01-02")
		info[date] = info[date] + 1
	}
	response.Success(c, info)
}

// 记录访问信息
func VisitLog(c *gin.Context) {
	url := c.Query("url")
	if url == "" || len(url) > 190 {
		response.ValidateFail(c, "url错误", response.Validator{
			Field:   "url",
			Message: "url错误",
		})
		return
	}
	global.App.DB.Create(&models.Visits{
		IP:     utils.GetRealIP(c),
		Router: url,
	})
	response.Success(c, gin.H{})
}

// 发送邮件
func SendMail(c *gin.Context) {
	var form request.SendMail

	from := global.App.Config.Mail.User
	password := global.App.Config.Mail.Password
	smtpHost := global.App.Config.Mail.SMTPHost
	smtpPort := global.App.Config.Mail.SMTPPort

	// if err := c.ShouldBindJSON(&form); err != nil {
	// 	response.ValidateFail(c, request.GetErrorMsg(form, err))
	// 	return
	// }
	if !services.Request(c, &form) {
		return
	}

	body := "<strong>xxxx</strong>"

	sender := &MailSender{
		To:          form.To,
		From:        from,
		NickName:    "癸亥王",
		Title:       "测试邮件",
		ContentType: "Content-Type: text/html; charset=utf-8",
		Body:        body + form.Message,
	}
	s := fmt.Sprintf("To:%s\r\nFrom:%s<%s>\r\nSubject:%s\r\n%s\r\n\r\n%s",
		sender.To, sender.NickName, sender.From, sender.Title, sender.ContentType, sender.Body)

	auth := smtp.PlainAuth("", from, password, smtpHost)
	// fmt.Println("auth,", auth)
	err := smtp.SendMail(smtpHost+":"+strconv.Itoa(smtpPort), auth, from, []string{form.To}, []byte(s))
	if err != nil {
		fmt.Println("err,", err.Error())
	}
	response.Success(c, "发送成功")
}

type MailSender struct {
	To          string `json:"to"`
	From        string `json:"from"`
	NickName    string `json:"nick_name"`
	Title       string `json:"title"`
	ContentType string `json:"content_type"`
	Body        string `json:"body"`
}
